<template>
  <div class="household-register">
    <el-card>
      <template #header>
        <span>家庭户口立户</span>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="户主姓名" prop="householderName">
              <el-input v-model="form.householderName" placeholder="请输入户主姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="户口类型" prop="householdType">
              <el-select v-model="form.householdType" placeholder="请选择户口类型" style="width: 100%">
                <el-option label="家庭户" :value="1" />
                <el-option label="集体户" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 地址信息 -->
        <el-divider content-position="left">地址信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="省份" prop="province">
              <el-input v-model="form.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="城市" prop="city">
              <el-input v-model="form.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县" prop="district">
              <el-input v-model="form.district" placeholder="请输入区县" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="街道" prop="street">
              <el-input v-model="form.street" placeholder="请输入街道" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社区" prop="community">
              <el-input v-model="form.community" placeholder="请输入社区" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮政编码" prop="postalCode">
              <el-input v-model="form.postalCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="派出所" prop="policeStation">
              <el-input v-model="form.policeStation" placeholder="请输入派出所" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细户籍地址"
          />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            提交申请
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'

const formRef = ref()
const loading = ref(false)

// 表单数据 - 对应后端 HouseholdInfoBO
const form = reactive({
  householderName: '',
  idCard: '',
  householdType: 1, // 默认家庭户
  address: '',
  province: '',
  city: '',
  district: '',
  street: '',
  community: '',
  postalCode: '',
  policeStation: '',
  remark: ''
})

// 表单验证规则
const rules = {
  householderName: [
    { required: true, message: '请输入户主姓名', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  householdType: [
    { required: true, message: '请选择户口类型', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细户籍地址', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区县', trigger: 'blur' }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      // 获取token
      const token = localStorage.getItem('token')
      if (!token) {
        ElMessage.error('请先登录')
        return
      }

      console.log('发送立户请求，数据:', form)
      
      // 发送请求到后端
      const response = await axios.post(`${API_BASE_URL}/household/register`, form, {
        headers: {
          'token': token,
          'Content-Type': 'application/json'
        }
      })
      
      console.log('立户响应:', response.data)
      
      // 处理响应结果
      const result = response.data
      
      if (result.status === 200) {
        // 立户成功
        ElMessage.success(result.msg || '立户申请提交成功')
        // 重置表单
        handleReset()
      } else {
        // 立户失败
        ElMessage.error(result.msg || '立户申请提交失败')
      }
      
    } catch (error) {
      console.error('立户请求出错:', error)
      
      if (error.response) {
        // 服务器返回了错误状态码
        const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        // 请求发出但没有收到响应
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        // 其他错误
        ElMessage.error('立户申请失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  })
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.household-register {
  .el-form {
    max-width: 900px;
  }

  .el-divider {
    margin: 20px 0;
  }

  .el-divider__text {
    font-weight: 600;
    color: #409eff;
  }
}
</style>